<?php
namespace App\Observers;

use Eloquent;

/**
 * 无限极分类观察者
 * Class SortObserver
 * @package App\Observers
 */
class SortObserver {

    public function creating(Eloquent $owner)
    {
        if ($owner->fid) {
            /** @var  $class Eloquent*/
            $class = get_class($owner);
            $parent = $class::find($owner->fid);
            //排序
            $owner->sort = $parent->sort . ',' . $parent->id;
        }else{
            $owner->sort = 0;
        }
    }
    /**
     * 删除前
     * @param $event
     */
    public function deleting(Eloquent $owner)
    {
        if ($owner->sort == '') {
            $sort = $owner->fid;
        } else {
            $sort = $owner->sort . "," . $owner->id;
        }
        /** @var  $class Eloquent*/
        $class = get_class($owner);
        $children = $class::where("sort" ,'like',$sort.'%')->get();
        foreach($children as $child){
            $child->delete();
        }
    }
}